Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
Cree un diccionario con LINQ y evite el error "ya se agregó un elemento con la misma clave"

Quiero encontrar una clave en un diccionario y reemplazar el valor si se encuentra o agregar la clave/valor si no lo es.

Código:

 public class MyObject { public string UniqueKey { get; set; } public string Field1 { get; set; } public string Field2 { get; set; } }

Solución LINQ (lanza An item with the same key has already been added. ):

 Dictionary<string, MyObject> objectDict = csvEntries.ToDictionary(csvEntry => csvEntry.ToMyObject().UniqueKey, csvEntry => csvEntry.ToMyObject());

ForEach solución (funciona):

 Dictionary<string, MyObject> objectDict = new Dictionary<string, MyObject>(); foreach (CSVEntry csvEntry in csvEntries) { MyObject obj = csvEntry.ToMyObject(); if (objectDict.ContainsKey(obj.UniqueKey)) { objectDict[obj.UniqueKey] = obj; } else { objectDict.Add(obj.UniqueKey, obj); } }

Realmente me gustó la solución LINQ, pero tal como está, arroja el error anterior. ¿Hay alguna buena manera de evitar el error y usar LINQ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede usar GroupBy para crear claves únicas:

 Dictionary<string, MyObject> objectDict = csvEntries .Select(csvEntry => csvEntry.ToMyObject()) .GroupBy(x => x.UniqueKey) .ToDictionary(grp => grp.Key, grp => grp.First());

Sin embargo, en lugar de grp.First() , podría crear una colección con ToList o ToArray . De esa manera, no toma un objeto arbitrario en caso de claves duplicadas.

Otra opción es usar Lookup<TKey, TValue> que permite claves duplicadas e incluso claves inexistentes, obtienes una secuencia vacía en ese caso.

 var uniqueKeyLookup = csvEntries .Select(csvEntry => csvEntry.ToMyObject()) .ToLookup(x => x.UniqueKey); IEnumerable<MyObject> objectsFor1234 = uniqueKeyLookup["1234"]; // empty if it doesn't exist
over 4 years ago · Santiago Trujillo Report

0

Sobre la base de la respuesta de Tim, aquí hay un método de extensión que puede usar para que no necesite duplicar la implementación a lo largo de su proyecto:

 public static class DictionaryExtensions { public static Dictionary<TKey, TValue> ToDictionaryWithDupSelector<TKey, TValue>( this IEnumerable<TValue> enumerable, Func<TValue, TKey> groupBy, Func<IEnumerable<TValue>, TValue> selector = null) { if (selector == null) selector = new Func<IEnumerable<TValue>, TValue>(grp => grp.First()); return enumerable .GroupBy(e => groupBy(e)) .ToDictionary(grp => grp.Key, grp => selector(grp)); } }

De manera predeterminada, elegirá el primer elemento cuando haya duplicados, pero proporcioné un parámetro opcional donde puede especificar un selector alternativo. Ejemplo de llamada al método de extensión:

 var objList = new List<string[]> { new string[2] {"1", "first"}, new string[2] {"1", "last"}, new string[2] {"2", "you"}, }; var asDict = objList.ToDictionary( arr => arr[0], grp => grp.Last() );
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!